package com.oceanstar.controller;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.UserInfoMapper;
import com.oceanstar.service.IChaperonService;
import com.oceanstar.service.IGridService;
import com.oceanstar.service.IUserInfoService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class GridController {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IGridService gridService;
    @Autowired
    private HealthController healthController;
    @Autowired
    private UserController userController;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /*
     *管理员将一个或多个老人分配给指定的网格员，实现绑定关系。
     */
    @PostMapping("/admin/grid/assign")
    public Result assignElder(@RequestBody Map<String, Object> map, @RequestHeader("token") String token) throws Exception {
        Integer gridId = (Integer) map.get("gridId");
        List<Integer> elderlyIds = (List<Integer>) map.get("elderlyIds");
        try {
            AssignedElderDTO dto = userInfoService.assignElderToGrid(gridId, elderlyIds, token);
            return Result.success(dto);
        } catch (Exception e) {
            return Result.error("分配失败: " + e.getMessage());
        }
    }

    /*
     *管理员解除网格员与指定老人的绑定关系。
     */
    @PostMapping("/admin/grid/unassign")
    public Result unassignElder(@RequestBody Map<String, Object> map, @RequestHeader("token") String token) throws Exception {
        Integer gridId = (Integer) map.get("gridId");
        List<Integer> elderlyIds = (List<Integer>) map.get("elderlyIds");
        try {
            UnassignedElderDTO dto = userInfoService.unassignElderToGrid(gridId, elderlyIds, token);
            return Result.success(dto);
        } catch (Exception e) {
            return Result.error("解除失败: " + e.getMessage());
        }
    }

    /*
     *管理员查看指定网格员当前已绑定的老人列表，可分页、可筛选。
     */
    @GetMapping("/admin/grid/bindings")
    public Result getGridBindings(
            @RequestParam Integer gridId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestHeader("token") String token) throws Exception {
        try {
            GridBindingsResponse res = userInfoService.getGridBindings(gridId, page, pageSize, name, token);
            return Result.success(res);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /*
     *网格员查看网格员绑定的老人列表
     */
    @GetMapping("/grid/elderly")
    public Result getGridElderly(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam(required = false) String name,
                                 @RequestHeader("token") String token) throws Exception {
        try {
            PageInfo<ElderBindingInfo> info = gridService.getGridElderly(page, pageSize, name, token);
            return Result.success(info);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /*
     * 网格员查看所绑定老人的心率数据 - 转发到现有接口
     */
    @GetMapping("/grid/health/heartRate")
    public Result getHeartRate(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getHeartRateHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的血压数据 - 转发到现有接口
     */
    @GetMapping("/grid/health/bloodPressure")
    public Result getBloodPressure(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getBloodPressureHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的血糖数据 - 转发到现有接口
     */
    @GetMapping("/grid/health/bloodSugar")
    public Result getBloodSugar(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getBloodSugarHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的体重数据 - 转发到现有接口
     */
    @GetMapping("/grid/health/weight")
    public Result getWeight(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getWeightHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的过敏史 - 转发到现有接口
     */
    @GetMapping("/grid/health/allergyHistory")
    public Result getAllergyHistory(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getAllergyHistoryHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的病史 - 转发到现有接口
     */
    @GetMapping("/grid/health/medicalHistory")
    public Result getMedicalHistory(@RequestParam("id") Integer id, @RequestHeader("token") String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的健康数据");
        }
        return healthController.getMedicalHistoryHistory(id, token);
    }

    /*
     * 网格员查看所绑定老人的家属信息 - 转发到现有接口
     */
    @GetMapping("/grid/family")
    public Result getFamilyInfo(@RequestParam("id") Integer id, @RequestHeader("token") String token) throws Exception {
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(identity == 4 && userInfo.getGridId() != claims.get("id")) {
            return Result.error("网格员只能查询关联老人的家属");
        }
        return userController.getFamilyBinding(id);
    }

    /*
     *该接口用于网格员查看所负责区域或绑定老人的历史报警记录（如跌倒、紧急求助等）。
     */
    @GetMapping("/grid/alerts/history")
    public Result getAlertHistory(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(required = false) Integer elderlyId,
                                  @RequestParam(required = false) String begin,
                                  @RequestParam(required = false) String end,
                                  @RequestHeader("token") String token) throws Exception {
        try {
            PageInfo<AlertHistoryDTO> info = gridService.getAlertHistory(page, pageSize, elderlyId, begin, end, token);
            return Result.success(info);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /*
     *该接口用于网格员查看所负责区域或绑定老人的历史报警记录（如跌倒、紧急求助等）。
     */
    @GetMapping("/grid/alerts/pending")
    public Result getPendingAlerts(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestHeader("token") String token) throws Exception {
        try {
            PageInfo<AlertPendingDTO> info = gridService.getPendingAlerts(page, pageSize, token);
            return Result.success(info);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /*
     * 处理报警
     */
    @PostMapping("/grid/alerts/handle")
    public Result handleAlert(@RequestBody AlertHandleRequest request, @RequestHeader("token") String token) {
        try {
            gridService.handleAlert(request, token);
            return Result.success();
        } catch (Exception e) {
            return Result.error("处理失败: " + e.getMessage());
        }
    }
}
